//
//  _2RegistViewController.swift
//  fsapp
//
//  Created by zguang on 17/8/1.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import Alamofire
import WCLImagePickerController
import AliyunOSSiOS
//import "<AliyunOSSiOS/OSSService.h>"
import SVProgressHUD
class _2RegistViewController: UIViewController,WCLImagePikcerDelegate{

    let registView = loginView(type:"regist2")
    var code  = String()
    var phoneNumber = String()
    var imageupload = NSData()
    var upjudge = false
    var client:OSSClient?
    var imgUrl:String?
    var sessionID  = String()
    
    //MARK: - imagepick 的协议实现
    
    func wclImagePickerCancel(_ picker: WCLImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func wclImagePickerComplete(_ picker: WCLImagePickerController, imageArr: [UIImage]) {
        picker.dismiss(animated: true, completion: nil)
        //self.imagepick = imageArr
        for i in imageArr{
         //self.upjudge = true
          self.imageupload = i.compressImage(image: i, maxLength: 1024*1024)!
          self.registView.upImageButton.setImage(i, for: .normal)
        }
        if imageArr.count == 0{
           self.upjudge = false
        }else{
           self.upjudge = true
        }
        
        
       // print(imageupload)
    }
    
    func wclImagePickerError(_ picker: WCLImagePickerController, error: WCLError) {
        let al = UIAlertController.init(title: nil, message: error.lcalizable, preferredStyle: .alert)
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        al.addAction(cancel)
        picker.present(al, animated: true, completion: nil)
        
    }

    
    
    init(_ code:String,_ phoneNumber:String) {
        super.init(nibName: nil, bundle: nil)
        self.code = code
        self.phoneNumber = phoneNumber
    }
    
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.navigationItem.title = "注册"
        self.registView.upImageButton.addTarget(self, action: #selector(touchesPick), for: .touchUpInside)
        self.view.addSubview(registView.BackView)
        self.registView.upvisibleButton.addTarget(self, action: #selector(hidePassword1(_:)), for: .touchUpInside)
        self.registView.visibleButton.addTarget(self, action: #selector(hidePassword2(_:)), for: .touchUpInside)
        self.registView.loginNow.addTarget(self, action: #selector(complete), for: .touchUpInside)
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func hidePassword1(_ btn:UIButton){
       print(btn.isSelected)
        btn.isSelected = !btn.isSelected
        if btn.isSelected{
        self.registView.userText.isSecureTextEntry = false
        }else{
          self.registView.userText.isSecureTextEntry = true
        }
       
    }
    func hidePassword2(_ btn:UIButton){
        print(btn.isSelected)
         btn.isSelected = !btn.isSelected
       print(btn.isSelected)
        if btn.isSelected{
            self.registView.confirmPasswordText.isSecureTextEntry = false
        }else{
          self.registView.confirmPasswordText.isSecureTextEntry = true
        }
       
    }
    
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
          self.registView.accountText.resignFirstResponder()
         self.registView.codeText.resignFirstResponder()
         self.registView.passwordText.resignFirstResponder()
         self.registView.phoneText.resignFirstResponder()
         self.registView.userText.resignFirstResponder()
         self.registView.confirmPasswordText.resignFirstResponder()
    }
    
    func touchesPick(){
        WCLImagePickerController.present(inVC: self, delegate: self)
        WCLImagePickerOptions.maxPhotoSelectNum = 1
    }

    
    
    func complete(){
      
 
        print(registView.confirmPasswordText.text)
        if (self.registView.userText.text == registView.confirmPasswordText.text){
            if  upjudge{
              self.update(toALi2: self.imageupload as Data, code: self.code, phone: self.phoneNumber, name: self.registView.accountText.text!, password: self.registView.confirmPasswordText.text!)
            }else{
            Alarequest(data: "")
            }
        }else{
            let alert = UIAlertView(title: "提示", message: "两次输入的密码不一致", delegate: nil, cancelButtonTitle: "知道了")
            alert.show()
        }
    
    }
    
    
    
    // MARK: - 网络请求
    func Alarequest(data:String){
        
        let url = LOGIN_API_URL + "visitorLoginToRegister"
        let password = self.registView.confirmPasswordText.text!
        let name = self.registView.accountText.text!
        print(self.registView.confirmPasswordText.text)
        
        let paramdic =
            ["phoneNumber":phoneNumber,
             "name":name,
             "password":password,
             "code":Int(code),
             "img":data,
             ] as [String : Any]
      
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
            print("result=========================")
            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
            
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
                
                if let cookies =  HTTPCookieStorage.shared.cookies{
                    print(cookies)
                    self.saveCookies(response: response)
                    //          let usr = UserDefaults.standard
                    //  usr.set(cookies as [String:String], forKey: "savedCookies")
                    //  UserDefaults.standard.synchronize()
                    print(cookies)
                    for cookie in cookies{
                        self.sessionID = String(cookie.name)+("=") + String(cookie.value)
                    }
                }else {
                    print("登录出错,未获取到sessionID")
                    return
                }
                
                if self.sessionID == "" {
                    print("登录出错,未获取到sessionID")
                    //return
                }

                
                
                
                DispatchQueue.main.async {
                    if(js["status"]==200){
                        //bo = true
                        print(js)
                      
                        let load = LoadViewController()
                        self.present(load.CusTomTabBar(), animated: true, completion: nil)
                        
                        
                        let alert = UIAlertView(title: "提示", message: "注册成功", delegate: nil, cancelButtonTitle: "知道了")
                        alert.show()
                       // let load = LoadViewController()
                      // self.present(load.CusTomTabBar(), animated: true, completion: nil)
                        // self.navigationController?.popToRootViewController(animated: true)
                        //print(bo)
                    }
                        
                    else{
                        if js["status"] == 1002{
                            let alert = UIAlertView(title: "手机号已注册", message: "请重试", delegate: nil, cancelButtonTitle: "知道了")
                            alert.show()
                        }
                        if js["status"] == 1003{
                            let alert = UIAlertView(title: "验证码错误", message: "请重试", delegate: nil, cancelButtonTitle: "知道了")
                            alert.show()
                            self.navigationController?.popViewController(animated: true)
                        }
                        if js["status"] == 1004{
                            let alert = UIAlertView(title: "服务器出错", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                            alert.show()
                        }
                    }
                }
                
            }
        }
        
    }
    
    
    func Alarequest2(data:String,password:String,name:String){
        
        
        let url = LOGIN_API_URL + "register"
        //let password = self.registView.confirmPasswordText.text
        //let name = self.registView.accountText.text
       // print(self.registView.confirmPasswordText.text)
        
        let paramdic =
            ["phoneNumber":phoneNumber,
             "name":name,
             "password":password,
             "code":Int(code),
             "img":data,
             ] as [String : Any]
        
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
            print("result=========================")
            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
            
            if let cookies =  HTTPCookieStorage.shared.cookies{
                print(cookies)
                self.saveCookies(response: response)
                //          let usr = UserDefaults.standard
                //  usr.set(cookies as [String:String], forKey: "savedCookies")
                //  UserDefaults.standard.synchronize()
                print(cookies)
                for cookie in cookies{
                    self.sessionID = String(cookie.name)+("=") + String(cookie.value)
                }
            }else {
                print("登录出错,未获取到sessionID")
                return
            }
            
            if self.sessionID == "" {
                print("登录出错,未获取到sessionID")
                //return
            }

            
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
               // DispatchQueue.main.async {
                  
                //let load = LoadViewController()
                //self.performSegue(withIdentifier: "", sender: s)
                  //  self.present(load, animated: true, completion: nil)
                //    self.navigationController?.present(load, animated: true, completion: nil)
                    if(js["status"]==200){
                
                        
                    SVProgressHUD.dismiss(withDelay:2)
                        //bo = true
                        print(js)
                       // let alert = UIAlertView(title: "提示", message: "注册成功", delegate: nil, cancelButtonTitle: "知道了")
                       // alert.show()
                       SVProgressHUD.showSuccess(withStatus: "注册成功")
                        let usd = UserSave()
                        
                        usd.saveInfo("", self.phoneNumber,"", "0", self.registView.accountText.text!,"", self.imgUrl!, "", "", "", sessionID: self.sessionID)
                        let load = AppDelegate().CusTomTabBar()
                        self.present(load, animated: true, completion: nil)
                        // self.navigationController?.popToRootViewController(animated: true)
                        //print(bo)
                    }
                        
                    else{
                        if js["status"] == 0 {
                            SVProgressHUD.showError(withStatus: "信息填写错误，请检查")
                        }
                        
                        
                        if js["status"] == 1002{
                           
                            SVProgressHUD.showError(withStatus: "手机号已注册")
                            
                            
                            //let load = LoadViewController()
                           // load.viewDidLoad()
                          
                         //   self.present(load.CusTomTabBar(), animated: true, completion: nil)
                            
                            // let alert = UIAlertView(title: "手机号已注册", message: "请重试", delegate: nil, cancelButtonTitle: "知道了")
                           // alert.show()
                        }
                        if js["status"] == 1003{
                        SVProgressHUD.showError(withStatus: "验证码错误")
                            //   let alert = UIAlertView(title: "验证码错误", message: "请重试", delegate: nil, cancelButtonTitle: "知道了")
                          //  alert.show()
                            self.navigationController?.popViewController(animated: true)
                        }
                        if js["status"] == 1004{
                            SVProgressHUD.showError(withStatus: "服务器正忙，请稍后重试")
                           // let alert = UIAlertView(title: "服务器出错", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                            //alert.show()
                        }
                        
                    }
               // }
                
            }
        }
        
    }
    

    func initALi() {
        
        
        
        let endpoint:String =  "http://oss-cn-shenzhen.aliyuncs.com"
        let accesskeyId = "zlN0arcl6DMQpBTf"
        let accesskeySecret = "STDVRcq9CmVa7J6Iv2Y4l4LMweG48A"
        let credential: OSSCredentialProvider = OSSCustomSignerCredentialProvider {(contentToSign, error: NSErrorPointer) -> String? in
            
            let signture = OSSUtil.calBase64Sha1(withData: contentToSign, withSecret: accesskeySecret)
            if signture == nil {
                print(error!)
                return nil
            }
            return "OSS \(accesskeyId):\(signture!)"
        }
        
        client = OSSClient(endpoint: endpoint, credentialProvider: credential)
   
//       let clientConfig = ClientConfiguration()
//        clientConfig.connection_timetout = 30
//        clientConfig.retry_time = 3
//        client = OSSClient(endpoint: endpoint, accessKeyId: accesskeyId, accessKeySecret: accesskeySecret,  config: clientConfig)

        // let credential: OSSCredentialProvider = OSSPlainTextAKSKPairCredentialProvider(plainTextAccessKey: "zlN0arcl6DMQpBTf", secretKey: "STDVRcq9CmVa7J6Iv2Y4l4LMweG48A")
       // let conf = OSSClientConfiguration()
        //网络请求遇到异常失败后重复的次数
       // conf.maxRetryCount = 3
        //网络请求超时事件
       // conf.timeoutIntervalForRequest = 30
        //允许资源传输的最长时间
        //conf.timeoutIntervalForResource = TimeInterval(24 * 60 * 60)
        //阿里地址
       // client = OSSClient(endpoint: "http://oss-cn-shenzhen.aliyuncs.com", credentialProvider: credential)
    }
    
    
    
    func update(toALi2 data: Data, code Code: String, phone: String, name Name: String, password: String) {
       
        initALi()
        //put.bucketName = "dahan-img"
        var date = Date(timeIntervalSinceNow: 0)
        let a: TimeInterval = date.timeIntervalSince1970
        let x = Int(a)
        date = Date()
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        formatter.dateFormat = "YYYY-MM-dd"
        let dateTime: String = formatter.string(from: date)
        let objectKey: String = "Picture/head/\(dateTime)/\(Int(x))_\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10)\(arc4random() % 10).jpg"
        let str: String = "http://img.dahan.cn/\(objectKey)"
        imgUrl = "http://dahan-img.oss-cn-shenzhen.aliyuncs.com/\(objectKey)"
        //let vc = _2RegistViewController.init(Code, phone)
        self.Alarequest2(data: imgUrl!, password: password, name: Name)
        print(imgUrl)
        let put = OSSPutObjectRequest.init()
        put.objectKey = objectKey
        put.uploadingData = data
        put.uploadProgress = {(_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void in
            print("\(bytesSent),\(totalBytesSent),\(totalBytesExpectedToSend)")
           }
        // PutObjectRequest(bucketName: "dahan-img", key: objectKey, data: data)
      
        client?.putObject(put)
        
//        client?.putObject(request: put, onCompletion: {
//            (success,result,error) in
//            if success {
//                 print("上传成功")
//            }else{
//               print(error ?? "" as! Error)
//            }
//
//        })
////
//        // put.objectKey = objectKey
//       // put.uploadingData = data
//      //  put.uploadProgress = {(_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void in
//      //      print("\(bytesSent),\(totalBytesSent),\(totalBytesExpectedToSend)")
//      //  }
    
    }
    
 
     //   putTask?.continue(withBlock:     /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    //  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    //}
    //*/
 
    
    func saveCookies(response: DataResponse<Any>) {
        let headerFields = response.response?.allHeaderFields as! [String: String]
        let url = response.response?.url
        //let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
        if let cookies =  HTTPCookieStorage.shared.cookies{
            var cookieArray = [[HTTPCookiePropertyKey: Any]]()
            for cookie in cookies {
                cookieArray.append(cookie.properties!)
            }
            UserDefaults.standard.set(cookieArray, forKey: "savedCookies")
            UserDefaults.standard.synchronize()
            print(cookies)
        }
    }


}
